﻿#region Copyright Notice
/*
 
DarkLakeTools, Dark Lake Software, Inc. (Provides Performance Enhancing Tools For ASP.NET applications)
Copyright (C) 2009  Dark Lake Software, Inc. 

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

Dark Lake Software, Inc. 
Postal Box 916461
Longwood, FL  32791
admin@darklakesoftware.com
 
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Configuration;
using DarkLakeTools.Configuration; 

namespace DarkLakeTools.CSSUtility
{
    class CSSUtility : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            DarkLakeSection config = (DarkLakeSection)ConfigurationManager.GetSection("darkLakeSection");

            context.Response.Clear();
            context.Response.ContentType = "text/css"; // Used so that IIS7 will compress the file as well. 

            StringBuilder sb = new StringBuilder();

            if (context.Cache["DarkLakeTools.CSSUtility"] != null)
            {
                sb.Append(context.Cache["DarkLakeTools.CSSUtility"].ToString());
            }
            else
            {
                foreach (string file in System.IO.Directory.GetFiles(context.Server.MapPath(config.CSSUtility.CSSDirectory), "*.css"))
                {
                    sb.Append(System.IO.File.ReadAllText(file, Encoding.Default));
                }

                string FinalCss;
                if (config.CSSUtility.StripWhiteSpace)
                {
                    FinalCss = CompressCSS.Compress(sb.ToString()); 
                }
                else
                {
                    FinalCss = sb.ToString(); 
                }

                lock (context.Cache)
                {
                    context.Cache.Add("DarkLakeTools.CSSUtility", FinalCss, null, System.Web.Caching.Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); 

                }
            }
            context.Response.Write(sb.ToString()); 
            
        }

        #endregion
    }
}
